import React from 'react';
import {Image, Keyboard, Modal, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View,} from 'react-native';
import Constants from '../utils/Constants';
import screen from '../utils/screen';
import RequestUtil from '../utils/RequestUtil';
import DialogTip from '../widgets/modal/DialogTip';
import Api from '../utils/Api';
import {AppInfo, FontFamily, getffly} from '../utils/common';
import Images from '../images/Images';
import {LGBtn} from '../widgets/buttons';


export default  class VerifyDialog extends React.Component {

    constructor(props) {
        super(props);


    }

    state={
        modalVisible:false,
        mobile:'',
        code:'',
        enable:false,
        isSend:false,
        sendTime:0
    }


    componentDidMount = () => {

    }



    logout = ()=>{
        this.hideDialog()
        this.onConfirm && this.onConfirm();

    }

    sendCode = ()=>{
        Keyboard.dismiss()
        let param = {
            receiverType:'cellphone',
            receiverArea:AppInfo.countryId,
            receiverId:this.state.mobile
        }

        this.tipDialog.showLoading();

        let url = Api.sendCodeRegister
        if(this.isResetPsw){
            url = Api.sendCodeRetrieve
        }

        RequestUtil.post(url,param,true).then(res=>{
            console.log('send code',res)
            const data =res.data
            this.tipDialog.hideDialog()
            this.setState({
                codeText:data.code ? data.code : '',
                isSend:true,
                sendTime:60,
                enable:true
            },()=>{
                this.countDown()
            })

        },error=>{
            this.tipDialog.hideDialog()
            this.tipDialog.showError(error.msg)
        })
    }

    onValidate= ()=>{
        Keyboard.dismiss()
        let param = {
            receiverType:'cellphone',
            receiverArea:AppInfo.countryId,
            receiverId:this.state.mobile,
            code:this.state.code
        }

        this.tipDialog.showLoading();
        let url = Api.registerValidate
        if(this.isResetPsw){
            url = Api.retrieveValidate
        }
        console.log('validate',url)
        console.log('validate',param)
        RequestUtil.post(url,param,true).then(res=>{
            console.log('validate',res)
            const data =res.data
            this.tipDialog.hideDialog()
            this.hideDialog()
            this.onConfirm && this.onConfirm(this.state.code)

        },error=>{
            this.tipDialog.hideDialog()
            this.tipDialog.showError(error.msg)
        })
    }

    countDown = ()=>{
        this.timer = setInterval(()=>{
            let time  = this.state.sendTime - 1
            if(time >= 0){
                this.setState({
                    sendTime:time
                })
            }else{
                this.timer && clearInterval(this.timer)
                this.setState({
                    isSend:false,
                    sendTime:0
                })
            }
        },1000)
    }


    hideDialog = () => {

        this.timer && clearInterval(this.timer)
        this.setState({ modalVisible: false });
    }

    show = (mobile,onConfirm,isResetPsw)=>{
        this.isResetPsw = isResetPsw
        this.onConfirm = onConfirm
        this.setState({
            mobile,
            enable:false,
            modalVisible:true
        })
    }

    renderContent(){
        const mobile = this.state.mobile
        const mobileStr = mobile.substring(0,2) + '****' + mobile.substring(mobile.length - 2)
        let sentStr = `${Constants.login.code_will_be_sent_to } ${mobileStr}`

        return (
            <View style={styles.innerContainer}>

                <Text style={styles.title}>{Constants.login.verification}</Text>

                <View style={styles.contentBg}>
                    <Text style={{fontSize:14,color:'#8A8A8A'}}>{`${Constants.login.enter} ${Constants.login.mobile} ${Constants.login.verification_code}`}</Text>

                    <View style={styles.codeInputWrap}>
                        <TextInput
                            keyboardType='numeric'
                            allowFontScaling={false}
                            placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                            placeholder={Constants.login.verification}
                            style={ styles.codeInput}
                            value={this.state.code}
                            onChangeText={(text) => {
                                this.setState({
                                    code:text
                                })

                            }}
                        />

                        {
                            !this.state.isSend ? (
                                <TouchableOpacity
                                    style={styles.sendBtn}
                                    onPress={()=>this.sendCode()}
                                >
                                    <Text style={{color:'#377C74',fontSize:20,}}>{Constants.login.send_code}</Text>
                                </TouchableOpacity>
                            ):(
                                <View
                                    style={[styles.sendBtn,{borderColor:'#C8C8C8' }]}
                                >
                                    <Text style={{color:'#C8C8C8',fontSize:20,}}>{`${this.state.sendTime} s`}</Text>
                                </View>
                            )
                        }


                    </View>

                    <Text style={{fontSize:14,color:'#8A8A8A',marginTop:screen.PIXEL_30}}>{sentStr}</Text>

                </View>

                {
                    this.state.enable>  0 ? (
                        <LGBtn
                            title={Constants.login.confirm}
                            style={{width:'100%',height:screen.PIXEL_80,marginTop:screen.PIXEL_40}}
                            onPress={()=>this.onValidate()}
                        />
                    ) : (
                        <View style={ styles.btnGray}>
                            <Text style={{color:'#fff',fontSize:16}}>{Constants.login.confirm}</Text>
                        </View>
                    )
                }




            </View>

        )
    }



    render() {




        return (
            <Modal
                animationType={'none'}
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => { this._setModalVisible(false) }}
                onShow={this.startShow}
            >
                <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false} />
                <TouchableOpacity
                    activeOpacity={1.0}
                    onPress={() => {

                    }}
                    style={styles.bottomcontainer}>

                    <View style={styles.container}>

                        {this.renderContent()}

                        <TouchableOpacity
                            style={{marginTop:screen.PIXEL_60}}
                            onPress={()=>{
                                this._setModalVisible(false)
                            }}
                        >
                            <Image source={Images.close} style={styles.close}/>
                        </TouchableOpacity>

                    </View>
                    <DialogTip ref={ref=>{this.tipDialog = ref}} />
                </TouchableOpacity>
            </Modal>
        );
    }


    _setModalVisible = (visible) => {
        this.setState({ modalVisible: visible });
    }

    startShow = () => {

    }
}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    innerContainer: {
        width: screen.width - screen.PIXEL_100,
        padding:screen.PIXEL_40,
        backgroundColor: '#FFFFFF',
        justifyContent:'center',
        alignItems: 'center',
        borderRadius: screen.PIXEL_50
    },

    close:{
        width:screen.PIXEL_70,
        height:screen.PIXEL_70
    },
    codeInputWrap:{
        marginTop:screen.PIXEL_40,
        width:'100%',
        height:screen.PIXEL_80,
        flexDirection:'row',
        justifyContent:'flex-end'
    },
    bottomcontainer: {
        zIndex: 2,
        flex: 1,
        alignItems: 'center',
        backgroundColor: 'rgba(16, 17, 22,0.75)',
        justifyContent: 'flex-end',
    },
    title:{
        color:'#377C74',fontSize:19,fontFamily:getffly(FontFamily.medium),textAlign:'center'
    },
    contentBg:{
        marginTop: screen.PIXEL_40,width:'100%'

    },codeInput:{
        width:'100%',
        fontFamily: getffly(FontFamily.bold),
        fontSize:20,
        padding:0,
        color:'#000',
        marginRight:6,
        borderBottomWidth:1,
        borderBottomColor:'rgba(32,32,32,0.3)'
    }, sendBtn:{
        width:screen.PIXEL_200,height:screen.PIXEL_80,borderWidth:2,
        borderColor:'#377C74',borderRadius: screen.PIXEL_40,
        justifyContent: 'center',
        alignItems:'center'
    },btnGray:{
        backgroundColor:'#C1C1C1',height:screen.PIXEL_80,width:'100%',marginTop:screen.PIXEL_40,
        borderRadius:screen.PIXEL_40,justifyContent:'center',alignItems:'center'
    }

});



